package common

import (
	"encoding/json"
	"fmt"
	_ "golang_start/config/init"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"

	// "golang_start/config/mysql"
	"golang_start/config/redis"

	"github.com/e421083458/golang_common/lib"
	_ "github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

/*
*定义基本返回CODE
 */
var SUCCESS_CODE int = 200 //成功
var FAIL_CODE int = 500    //错误
var NOT_LOGIN int = 201    //未登录

// var DB = mysql.DB

var DB *gorm.DB
var ApiURL string

func init() {
	// if err := lib.InitModule("./config/dev/", []string{"base", "mysql", "redis"}); err != nil {
	// 	log.Fatal(err)
	// 	fmt.Println("加载错误")
	// }
	// defer lib.Destroy()
	lib.Log.TagInfo(lib.NewTrace(), lib.DLTagUndefind, map[string]interface{}{"message": "todo sth"})
	ApiURL = lib.GetStringConf("base.http.apiurl")
	dbpool, err := lib.GetGormPool("default")
	if err != nil {
		fmt.Println("数据库连接失败", err.Error())
	}
	//事务
	// DB = dbpool.Begin()
	DB = dbpool
	// dbpool.Commit()
	// defer lib.Destroy()

}

/***************************************公共方法**********************************************/

func Lock(name string, code string) {
	redis.Set("Lock"+name, code, 60)
}
func Unlock(name string) {
	redis.Del(name)
}

func SendCode(phone string) (string, bool) {
	apiurl := lib.GetStringConf("base.message.apiurl")
	apikey := lib.GetStringConf("base.message.key")
	tempid := lib.GetStringConf("base.message.tempid")
	rediskey := redis.Get("Lock" + phone)

	if rediskey != "" {
		return "请不要重复发送验证码", false
	}
	code := fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	tpl_value := "#code#=" + code
	result, err := SendRequest("GET", apiurl, map[string]interface{}{"key": apikey, "tpl_id": tempid, "mobile": phone, "tpl_value": tpl_value}, nil)
	if err {
		Lock(phone, code)
	}
	fmt.Println(result)
	return result, err
}

/*
*统一请求方法
@params
请求方式 GET POST
请求地址
请求参数
请求header 默认nil

*/

func SendRequest(method string, apiurl string, params map[string]interface{}, header *map[string]string) (string, bool) {
	request_body := strings.NewReader("")
	if method == "GET" {
		param := url.Values{}
		URL, _ := url.Parse(apiurl)
		for k, v := range params {
			param.Set(k, v.(string))
		}
		URL.RawQuery = param.Encode()
		apiurl = URL.String()
	}

	if method == "POST" {
		json_params, _ := json.Marshal(params)
		request_body = strings.NewReader(string(json_params))
	}
	request, err := http.NewRequest(method, apiurl, request_body)

	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), false
	}
	if header != nil {
		for k, v := range *header {
			request.Header.Add(k, v)
		}
	}
	// request.Header.Add("Connection", "keep-alive")
	// request.Header.Add("Upgrade-Insecure-Requests", "1")
	// request.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")

	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		return err.Error(), false
	}
	defer resp.Body.Close()
	response, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err.Error(), false
	}
	return string(response), true
}
